import sys

from PyQt6.QtWidgets import QApplication, QWidget, QLineEdit, QMenu


class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.setWindowTitle('QMenu 测试')
        self.lb = QLineEdit('初始文本...', self)
        self.lb.move(100, 160)
        self.lb.resize(120, 40)

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        action1 = menu.addAction('1# 菜单项')
        action2 = menu.addAction('2# 菜单项')
        menu.addSeparator()
        menu.addAction('3# 菜单项')
        action1.triggered.connect(lambda: self.lb.setText('选项 1# 菜单项'))
        action2.triggered.connect(lambda: self.lb.setText('选项 2# 菜单项'))
        # 显示菜单
        menu.exec(event.globalPos())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    sys.exit(app.exec())
